module Admins
  class AdminsController < ControllerBase
    before_action :authenticate_root_admin
    before_action :set_admin, only: [:show, :update, :destroy]

    # GET /admins/admins
    def index
      @admins = Admin.all.page(params[:page]).per(params[:per])

      render_page @admins
    end

    # GET /admins/admins/1
    def show
      render json: @admin
    end

    # POST /admins/admins
    def create
      @admin = Admin.new(admin_params)

      if @admin.save
        render json: @admin, status: :created, location: [:admins, @admin]
      else
        render json: @admin.errors, status: :unprocessable_entity
      end
    end

    # PATCH/PUT /admins/admins/1
    def update
      if @admin.root?
        username = params.delete(:username)
        return render json: {username: ['不能修改root管理员的用户名']}, status: :unprocessable_entity if username.present? and username != @admin.username
      end
      if @admin.update(admin_params)
        render json: @admin
      else
        render json: @admin.errors, status: :unprocessable_entity
      end
    end

    # DELETE /admins/admins/1
    def destroy
      return render json: {root: ['不能删除']}, status: :unprocessable_entity if @admin.root?
      if @admin.destroy
        head :no_content
      else
        render json: @admin.errors, status: :unprocessable_entity
      end
    end

    private

    # Use callbacks to share common setup or constraints between actions.
    def set_admin
      @admin = Admin.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def admin_params
      params.permit(:username, :password)
    end

    def authenticate_root_admin
      head :forbidden unless current_admin.root?
    end
  end
end